import browser from "@/common/browser";
export default {
  // 补0方法
  formatZero(num, len) {
    if (String(num).length > len) return num;
    return (Array(len).join(0) + num).slice(-len);
  },
  // localStorage存储
  setStore(name, content) {
    let contentClone = content;
    if (!name) return;
    if (typeof content !== "string") {
      contentClone = JSON.stringify(contentClone);
    }
    window.localStorage.setItem(name, contentClone);
  },
  // localStorage获取
  getStore(name) {
    if (!name) return null;
    return window.localStorage.getItem(name);
  },
  // localStorage删除
  removeStore(name) {
    if (!name) return;
    window.localStorage.removeItem(name);
  },
  // 日期格式化
  dateFormat(str, type) {
    let date = new Date(str);
    let year = date.getFullYear();
    let month = this.formatZero(date.getMonth() + 1, 2);
    let day = this.formatZero(date.getDate(), 2);
    let hour = this.formatZero(date.getHours(), 2);
    let minute = this.formatZero(date.getMinutes(), 2);
    let seconds = this.formatZero(date.getSeconds(), 2);
    if (type == "YYYY-MM-DD") {
      return `${year}-${month}-${day}`;
    } else if (type == "YYYY-MM-DD HH:MM:SS") {
      return `${year}-${month}-${day} ${hour}:${minute}:${seconds}`;
    } else if (type == "MM/DD  HH:MM:SS") {
      return `${month}/${day} ${hour}:${minute}:${seconds}`;
    }
  },
  // 获取当前时间前后N天前后日期
  getDateBefore(dayCount) {
    var date = new Date();
    date.setDate(date.getDate() + dayCount);
    let year = date.getFullYear();
    let month = this.formatZero(date.getMonth() + 1, 2);
    let day = this.formatZero(date.getDate(), 2);
    return `${year}-${month}-${day}`;
  },
  /**
   * 数字转整数 如 100000 转为10万
   * @param {需要转化的数} num
   * @param {需要保留的小数位数} point
   */
  tranNumber(num, point) {
    let numStr = num.toString();
    // 十万以内直接返回
    if (numStr.length < 6) {
      return numStr;
    }
    //大于8位数是亿
    else if (numStr.length > 8) {
      let decimal = numStr.substring(
        numStr.length - 8,
        numStr.length - 8 + point
      );
      return parseFloat(parseInt(num / 100000000) + "." + decimal) + "亿";
    }
    //大于6位数是十万 (以10W分割 10W以下全部显示)
    else if (numStr.length > 5) {
      let decimal = numStr.substring(
        numStr.length - 4,
        numStr.length - 4 + point
      );
      return parseFloat(parseInt(num / 10000) + "." + decimal) + "万";
    }
  },
  // 格式化时间毫秒转分秒
  formatTime(time) {
    // 取整
    time = ~~time;
    var formatTime;
    if (time < 10) {
      formatTime = "00:0" + time;
    } else if (time < 60) {
      formatTime = "00:" + time;
    } else {
      var m = ~~parseInt((time % (1000 * 60 * 60)) / (1000 * 60));
      if (m < 10) {
        m = "0" + m;
      }
      var s = ~~parseInt((time % (1000 * 60)) / 1000);
      if (s < 10) {
        s = "0" + s;
      }
      formatTime = m + ":" + s;
    }
    return formatTime;
  },
  // 转换成秒
  formatSecond(time) {
    // 取整
    time = ~~time;
    var secondTime;
    if (time < 10) {
      secondTime = "00:0" + time;
    } else if (time < 60) {
      secondTime = "00:" + time;
    } else {
      var m = ~~parseInt((time % (1000 * 60 * 60)) / (1000 * 60));
      var s = ~~parseInt((time % (1000 * 60)) / 1000);
      secondTime = Number(m * 60 + s);
    }
    return secondTime;
  },
  // 时间戳转00:00:00
  formatSecondTime(interval) {
    interval = interval | 0;
    const h = (interval / 3600) | 0;
    const m = ((interval % 3600) / 60) | 0;
    const s = interval % 60;
    return `${this.formatZero(h, 2)}:${this.formatZero(m, 2)}:${this.formatZero(
      s,
      2
    )}`;
  },
  // 00:00:00转时间戳
  formatTimestamp(time) {
    if (time !== null) {
      var s = "";
      var hour = time.split(":")[0];
      var min = time.split(":")[1];
      var sec = time.split(":")[2];
      s = Number(hour * 3600) + Number(min * 60) + Number(sec);
      return s;
    }
  },
  // 时间戳转换成几分钟前，几小时前，几天前
  formatMsgTime(dateTimeStamp) {
    var result = "";
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - dateTimeStamp;
    if (diffValue < 0) return;
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;
    if (monthC >= 1) {
      result = "" + parseInt(monthC) + "月前";
    } else if (weekC >= 1) {
      result = "" + parseInt(weekC) + "周前";
    } else if (dayC >= 1) {
      result = "" + parseInt(dayC) + "天前";
    } else if (hourC >= 1) {
      result = "" + parseInt(hourC) + "小时前";
    } else if (minC >= 1) {
      result = "" + parseInt(minC) + "分钟前";
    } else {
      result = "刚刚";
    }
    return result;
  },
  // 获取是几几后
  getAstro(timestamp) {
    let newDate = new Date();
    newDate.setTime(timestamp);
    let birthday = newDate.toLocaleDateString(timestamp);
    let birthdayArr = birthday.split("/");
    let year = birthdayArr[0].substring(birthdayArr[0].length - 2) + "后";
    let month = birthdayArr[1];
    let day = birthdayArr[2];
    return (
      year +
      " - " +
      "魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯".substr(
        month * 2 - (day < "102223444433".charAt(month - 1) - -19) * 2,
        2
      ) +
      "座"
    );
  },
  // 数组随机
  shuffle(arr) {
    let _arr = arr.slice();
    for (let i = 0; i < _arr.length; i++) {
      let j = this.getRandomInt(0, i);
      let t = _arr[i];
      _arr[i] = _arr[j];
      _arr[j] = t;
    }
    return _arr;
  },
  getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
  },
  //数组对象合并去重
  processingData(arr1, arr2) {
    let json = arr1.concat(arr2); //两个数组对象合并
    let newJson = []; //盛放去重后数据的新数组
    //循环json数组对象的内容
    for (let item1 of json) {
      let flag = true; //建立标记，判断数据是否重复，true为不重复
      //循环新数组的内容
      for (let item2 of newJson) {
        //让json数组对象的内容与新数组的内容作比较，相同的话，改变标记为false
        if (item1.contentId && item1.contentId == item2.contentId) {
          flag = false;
        } else if (item1.trackId && item1.trackId == item2.trackId) {
          flag = false;
        } else if (
          item1.catalogueId &&
          item1.catalogueId == item2.catalogueId
        ) {
          flag = false;
        } else if (item1.categoryId && item1.categoryId == item2.categoryId) {
          flag = false;
        } else if (item1.videoId && item1.videoId == item2.videoId) {
          flag = false;
        }
      }
      //判断是否重复
      if (flag) {
        newJson.push(item1);
      }
    }
    return newJson;
  },
  //这个方法不会影响原来的对象，而是返回一个新对象
  filterParams(obj) {
    var _newPar = {};
    for (var key in obj) {
      //如果对象属性的值不为空，就保存该属性（这里我做了限制，如果属性的值为0，保存该属性。如果属性的值全部是空格，属于为空。
      if (
        (obj[key] === 0 || obj[key] === false || obj[key]) &&
        obj[key].toString().replace(/(^\s*)|(\s*$)/g, "") !== ""
      ) {
        _newPar[key] = obj[key];
      }
    }
    return _newPar;
  },
  // 给数组所有对象添加属性
  addArrItem(arr, ...objs) {
    var newArr = [];
    arr.map((item) => {
      newArr.push(Object.assign(item, ...objs));
    });
    return newArr;
  },
  generateUUID() {
    var d = new Date().getTime();
    var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
      /[xy]/g,
      function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
      }
    );
    return uuid;
  },
  //时间戳转日期
  formateDate(value) {
    if (value == null) {
      return "";
    } else {
      let date = new Date(value);
      let y = date.getFullYear(); // 年
      let MM = date.getMonth() + 1; // 月
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate(); // 日
      d = d < 10 ? "0" + d : d;
      let h = date.getHours(); // 时
      h = h < 10 ? "0" + h : h;
      let m = date.getMinutes(); // 分
      m = m < 10 ? "0" + m : m;
      let s = date.getSeconds(); // 秒
      s = s < 10 ? "0" + s : s;
      return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
    }
  },
  getUserIP(onNewIP) {
    let MyPeerConnection =
      window.RTCPeerConnection ||
      window.mozRTCPeerConnection ||
      window.webkitRTCPeerConnection;
    let pc = new MyPeerConnection({
      iceServers: [],
    });
    let noop = () => {};
    let localIPs = {};
    let ipRegex =
      /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
    let iterateIP = (ip) => {
      if (!localIPs[ip]) onNewIP(ip);
      localIPs[ip] = true;
    };
    pc.createDataChannel("");
    pc.createOffer()
      .then((sdp) => {
        sdp.sdp.split("\n").forEach(function (line) {
          if (line.indexOf("candidate") < 0) return;
          line.match(ipRegex).forEach(iterateIP);
        });
        pc.setLocalDescription(sdp, noop, noop);
      })
      .catch(() => {});
    pc.onicecandidate = (ice) => {
      if (
        !ice ||
        !ice.candidate ||
        !ice.candidate.candidate ||
        !ice.candidate.candidate.match(ipRegex)
      )
        return;
      ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
    };
  },
  //判断浏览器类型
  // isIE() {
  //   if (window.ActiveXObject || "ActiveXObject" in window) {
  //     return true;
  //   } else {
  //     return false;
  //   }
  // },
  //判断pc/移动端
  // _isMobile() {
  //   let flag = navigator.userAgent.match(
  //     /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
  //   );
  //   if (flag) {
  //     return true;
  //   } else {
  //     return false;
  //   }
  //   // return flag;
  // },
  //IE浏览器保存文本框内容
  IEDownloadFile(url) {
    var iframe = document.createElement("iframe");
    iframe.style.display = "none"; // 防止影响页面
    iframe.style.height = 0; // 防止影响页面
    iframe.src = url;
    document.body.appendChild(iframe); // 这一行必须，iframe挂在到dom树上才会发请求
    setTimeout(() => {
      iframe.remove();
    }, 6 * 60 * 1000);
    // // 保存页面 -> 保存文件
    // ifr.contentWindow.document.execCommand("SaveAs", false, fileName);
    // document.body.removeChild(ifr);
  },
  //单个下载
  downRow(url, fileName, type) {
    // 判断是否是IE浏览器，是的话返回true
    if (browser.isIE) {
      this.IEDownloadFile(url, `${fileName}.${type}`);
    } else {
      if (browser.isMobile && !browser.Sys.safari) {
        if (type === "pdf") {
          window.open(url, "_blank");
        }
        // if (type === "pdf") {
        //   if (browser.Sys.safari) {
        //     let ele = document.createElement("a");
        //     ele.download = `${fileName}.${type}`;
        //     ele.style.display = "none";
        //     ele.href = url;
        //     document.body.appendChild(ele);
        //     ele.click();
        //     document.body.removeChild(ele);
        //   } else {
        //     window.open(url, "_blank");
        //   }
        // }
      } else {
        // let that = this;
        let oReq = new XMLHttpRequest();
        oReq.open("GET", url.substr(url.indexOf("//")), true);
        oReq.responseType = "blob";
        oReq.onload = function () {
          var content = oReq.response;
          var elink = document.createElement("a");
          elink.download = `${fileName}.${type}`;
          elink.style.display = "none";
          var blob = new Blob([content]);
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          document.body.removeChild(elink);
        };
        oReq.send();
      }
    }
  },
  //批量下载
  batch(batchArr, type) {
    // 判断是否是IE浏览器，是的话返回true
    if (browser.isIE) {
      batchArr.forEach((item) => {
        this.IEDownloadFile(item.url, `${item.name}.${type}`);
      });
    } else {
      // let that = this;
      let num = 5; //下载个数
      let time = 10000; //延迟时间
      for (let n = 0; n < batchArr.length / num; n++) {
        setTimeout(() => {
          batchArr.slice(n * num, (n + 1) * num).map((item) => {
            let oReq = new XMLHttpRequest();
            oReq.open("GET", item.url.substr(item.url.indexOf("//")), true);
            oReq.responseType = "blob";
            oReq.onload = function () {
              var content = oReq.response;
              var elink = document.createElement("a");
              elink.download = `${item.name}.${type}`;
              elink.style.display = "none";
              var blob = new Blob([content]);
              elink.href = URL.createObjectURL(blob);
              document.body.appendChild(elink);
              elink.click();
              document.body.removeChild(elink);
            };
            oReq.send();
          });
        }, time * n);
      }
    }
  },
};
